//
//  VC3ForImage.m
//  PCAForWar
//
//  Created by dllo on 16/2/24.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "VC3ForImage.h"
#import "ModelForPicScroll.h"
#import "CollecCellForScroll.h"
#import <Social/Social.h>

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface VC3ForImage () <UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, retain) NSMutableArray *arrPic;
@property (nonatomic, retain) UICollectionView *collectionView;
@property (nonatomic, retain) NSMutableArray *picArr;

@end

@implementation VC3ForImage

- (void)dealloc{
    
    _collectionView.dataSource = nil;
    _collectionView.delegate = nil;
    
    [_arrPic release];
    [_collectionView release];
    [_picArr release];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor blackColor];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"FenXiang"] style:UIBarButtonItemStylePlain target:self action:@selector(fenXiang)];
    self.navigationItem.rightBarButtonItems = @[ item2];
    
    [item2 release];
    
    [self handleData];
    
    [self createCollectionView];
    
}

#pragma mark 收藏,分享功能实现
- (void)fenXiang {
    
    // 1.判断平台是否可用(系统没有集成,用户设置账号)
    if (![SLComposeViewController isAvailableForServiceType:SLServiceTypeSinaWeibo]) {
        
        NSLog(@"设置界面设置自己的账号");
        
        NSURL *url = [NSURL URLWithString:@"prefs:root="];
        
        if ([[UIApplication sharedApplication] canOpenURL:url]) {
            
            [[UIApplication sharedApplication] openURL:url];
        }
        
        return;
    }
    
    // 2.创建分享控制器
    SLComposeViewController *composeVc = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeSinaWeibo];
    
    // 2.1.添加分享的文字
    [composeVc setInitialText:@"梦想还是要有的,万一实现了呢"];
    
    // 2.2.添加分享的图片
    [composeVc addImage:[UIImage imageNamed:@"8bc3dd5c103853439da2910c9213b07ecb808893.jpg"]];
    
    // 3.弹出控制器进行分享
    [self presentViewController:composeVc animated:YES completion:nil];
    
    // 4.设置监听发送结果
    composeVc.completionHandler = ^(SLComposeViewControllerResult reulst) {
        
        if (reulst == SLComposeViewControllerResultDone) {
            
            NSLog(@"用户发送成功");
            
        } else {
            
            NSLog(@"用户发送失败");
        }
    };
    
}

#pragma mark 解析数据
- (void)handleData {
    
    NSURL *url = [NSURL URLWithString:@"http://admin.militaryapp.china.com/News/NewsServlet.do"];
    
    // URLRequest(网络请求对象)
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    request.HTTPMethod = @"POST";
    
    NSString *str3 = @"&linkUrl=http%3A%2F%2Ftuku.military.china.com%2Fmilitary%2F%2Fhtml%2F";
    
    NSString *str4 = @"%2F";
    
    NSString *str = [NSString stringWithFormat:@"%@%@%@",str3,self.date,str4];
    
    NSString *str2 = @".htm&processID=getPicInfo&sessionId=1&";
    
    request.HTTPBody = [[NSString stringWithFormat:@"newsId=%ld%@%ld%@", self.ID, str, self.ID, str2] dataUsingEncoding:NSUTF8StringEncoding];
    
    [request addValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
    
    // session对象(通道)
    NSURLSession *session = [NSURLSession sharedSession];
    
    // 添加任务
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            // 解析
            NSError *errorOfJSON = nil;
            
            if (data == nil) {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"网络提示" message:@"哎呀, 没有网络了 *_*" preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:1 handler:^(UIAlertAction * _Nonnull action) {
                    
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    
                }];
                
                [alert addAction:action];
                
                [self presentViewController:alert animated:NO completion:^{
                    
                }];
                
                return;
                
            } else {
                
                id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorOfJSON];
                
                [self handleDidComplete:result];
                
            }
        });
    }];
    // 开始任务
    [task resume];
    
}

#pragma mark 处理解析后的数据
- (void)handleDidComplete:(id)result {
    
    self.arrPic = [NSMutableArray array];
    
    NSArray *arrDown = [result objectForKey:@"data"];
    
    if ([arrDown.class isSubclassOfClass:[NSMutableArray class]]) {
        
        for (NSDictionary *dic in arrDown) {
            
            ModelForPicScroll *model = [[ModelForPicScroll alloc] init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            [self.arrPic addObject:model];
            
            [model release];
        }
        
        
        // 思路1:将图片全部加载后传值
        
        //        dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
        //
        //        // 再找到当前工程里的主队列
        //        dispatch_queue_t mainQueue = dispatch_get_main_queue();
        //
        //        dispatch_async(queue, ^{
        //
        //            self.picArr = [NSMutableArray array];
        //
        //            for (NSInteger i = 0; i < self.arrPic.count; i++) {
        //
        //                NSString *strURL = [self.arrPic[i] PicUrl];
        //
        //                NSURL *url = [NSURL URLWithString:strURL];
        //
        //                NSData *data = [NSData dataWithContentsOfURL:url];
        //
        //                UIImage *image = [UIImage imageWithData:data];
        //
        //                [self.picArr addObject:image];
        //            }
        //
        //            // 找到主队列,然后对控件进行视图的内容刷新
        //            dispatch_async(mainQueue, ^{
        //                [self.collectionView reloadData];
        //                [self createCollectionView];
        //            });
        //        });
        
        
        // 思路2:加载一个图片传一个值
        self.picArr = [NSMutableArray array];
        
        for (ModelForPicScroll *model in self.arrPic) {
            
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                
                UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.PicUrl]]];
                
                if (image != nil) {
                    
                    [self.picArr addObject:image];
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [self.collectionView reloadData];
                });
                
            });
            
        }
        
    }
    
}

#pragma mark 创建collectionView 轮播图
- (void)createCollectionView {
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    
    flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - 64);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumLineSpacing = 0;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64) collectionViewLayout:flowLayout];
    
    [self.view addSubview:self.collectionView];
    
    [flowLayout release];
    
    [_collectionView release];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    self.collectionView.backgroundColor = [UIColor blackColor];
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    
    [self.collectionView registerClass:[CollecCellForScroll class] forCellWithReuseIdentifier:@"poolForScroll"];
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CollecCellForScroll *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolForScroll" forIndexPath:indexPath];
    
    [cell passModelPicScroll:self.picArr[indexPath.item]];
    
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.picArr.count;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
